package com.lpc.android.abc.base.exception;


import android.app.AlarmManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Looper;
import android.os.SystemClock;
import android.widget.Toast;

import com.lpc.android.abc.base.utils.ActivityStackManager;
import com.lpc.android.abc.base.utils.UIUtil;
import com.umeng.analytics.MobclickAgent;

/**
 * Created by lipc0113 on 2017/6/28 0028.
 */
public class CrashHandler implements Thread.UncaughtExceptionHandler {

    public void init() {
        Thread.UncaughtExceptionHandler defaultUncaughtExceptionHandler = Thread.getDefaultUncaughtExceptionHandler();
        Thread.setDefaultUncaughtExceptionHandler(this);
    }

    @Override
    public void uncaughtException(Thread thread, Throwable ex) {

        if (ex != null) {
            exitApp();
        }

    }

    private void exitApp() {

        new Thread() {
            public void run() {

                Looper.prepare();
                Toast.makeText(UIUtil.getContext(), "很抱歉,程序出现异常,即将退出.", Toast.LENGTH_SHORT)
                        .show();
                Looper.loop();
            }
        }.start();

        SystemClock.sleep(1500);

        //两次自启时间间隔<1分半将不自启
        SharedPreferences sp = UIUtil.getContext().getSharedPreferences("launchTime", Context.MODE_PRIVATE);
        long launchTime = sp.getLong("launchTime", 0L);
        if (System.currentTimeMillis() - launchTime >= 90L * 1000L) {

            sp.edit().putLong("launchTime", System.currentTimeMillis()).apply();

            //自启设定，并关闭之前的进程
            Intent i = UIUtil.getContext().getPackageManager().getLaunchIntentForPackage(
                    UIUtil.getContext().getPackageName());
            PendingIntent pendingIntent = PendingIntent.getActivity(UIUtil.getContext(),
                    0, i, PendingIntent.FLAG_ONE_SHOT);
            AlarmManager alarmManager = (AlarmManager) UIUtil.getContext()
                    .getSystemService(Context.ALARM_SERVICE);
            alarmManager.set(AlarmManager.RTC,
                    System.currentTimeMillis() + 1000, pendingIntent);
        }

        MobclickAgent.onKillProcess(UIUtil.getContext());

        ActivityStackManager.getInstance().clearAllActivity();

        android.os.Process.killProcess(android.os.Process.myPid());
        System.exit(1);
    }

}
